import { judgeLogin, getUrl, baseUrl } from '@/static/js/utils.js';
let getAuth = () => {
		judgeLogin();
		// alert('获取授权');
	},
	getPage = () => {
		let pages = getCurrentPages();
		return pages.length ? pages[pages.length - 1] : null;
	};
let model = {
	init: function ({
		url,
		method = 'post',
		query = {},
		data = {},
		callback,
		error,
		noToast = false,
		duration = 1500,
	}) {
		uni.request({
			url: getUrl({
				url:
					(url.indexOf('://') > -1 ? '' : baseUrl) +
					(url && url.indexOf('/') == 0 ? url.slice(1) : url),
				query,
			}), // 仅为示例，并非真实的接口地址
			method: method,
			data,
			header: {
				'content-type': 'application/json', // 默认值
				Authorization: 'Bearer bb0afd35c4164fcbadda05262eade7f3',
			},
			success(res) {
				// console.log(res);
				// if (res.header.authorization) {
				// 	uni.setStorageSync('token', res.header.authorization);
				// }
				if (url.indexOf('://') > -1 || (res.data && res.data.code == 0)) {
					callback ? callback(res.data) : null;
				} else {
					if (!noToast) {
						uni.showToast({
							icon: 'none',
							title: res?.data?.msg || res?.data?.errmsg,
							duration: duration,
						});
					}
					try {
						error ? error(res) : null;
					} catch (error) {}
				}
			},
			fail(error) {
				if (error.code === 'ECONNABORTED') {
					// console.log('连接超时，网络不加')
					uni.redirectTo({
						url: '/pages/error/NoNetwork',
					});
				} else if (error.response && error.response.status == 401) {
					// uni.removeStorageSync('token');
					const route = getPage();
					console.log(route);
					const noAuth = ['pages/index/index'];
					if (noAuth.indexOf(route) == -1) {
						getAuth();
					}
				} else {
					if (!noToast) {
						try {
							uni.showToast({
								icon: 'none',
								title: error.response?.data?.message,
							});
						} catch (error) {}
					}
				}
			},
			complete(res) {},
		});
	},
};
export default model;
